package com.find.answer.filter;

import com.alibaba.fastjson.JSON;
import com.find.answer.domain.http.Result;
import com.find.answer.domain.common.BaseContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 使用过滤器就每一偶任何问题，不知道为什么。。。有有待研究。
 * @author Seon
 * @date 2022/10/16 21:26
 */
@Slf4j
@WebFilter(filterName = "GlobalFilter", urlPatterns = "/*")
public class GlobalFilter implements Filter {

    private static final String EMPLOYEE = "employee";
    private static final String USER = "user";
    private static final String NOT_LOGIN = "NOT_LOGIN";
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        String[] excludeURL = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check = this.checkPath(excludeURL, uri);
        if (check) {
            filterChain.doFilter(request, response);
            return ;
        }
        HttpSession session = request.getSession();
        /*
        在上下文环境中设置employee或者user的id,
         */
        Long employeeId = (Long) session.getAttribute(EMPLOYEE);
        if (employeeId != null) {
            BaseContextHolder.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return ;
        }

        Long userId = (Long) session.getAttribute(USER);

//        log.info("userId = {}", userId);少加了一句return 啊啊啊啊阿。！！！
        if (userId != null) {
            BaseContextHolder.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return ;
        }
        log.info("用户未登录...");
        response.getWriter().write(JSON.toJSONString(Result.error(NOT_LOGIN)));
    }

    protected boolean checkPath(String[] excludeURL, String requestURI) {
        for (String url : excludeURL) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
